//基础配置。
/**
 * 提供后台配置接口，在本项目内部使用。用于创建标准实体，自定义实体。编辑、删除等操作。针对实体配置，非实体数据。
 */
var express = require("express");
var router = express.Router();
const ObjectConfig = require("../../../models/ObjectConfig.ts"); //拿到总配置信息。

var mongodb = require("../../../models/db.ts");
var ObjectID = require("mongodb").ObjectID;

var uuid = require("uuid");

var systemFields = require("../../../config/system_fields.json");

/**
 * 获取所有实体数据。(准备废弃，不能直接获取所有已存在的所有实体列表。)
 */

//@Api(name="/base/config/object/getAllObjectConfig")
router.get("/config/object/getAllObjectConfig", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  try {
    ObjectConfig.getObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let response = {
        code: 200,
        msg: "OK",
        data: configs,
      };
      res.send(response);
    });
  } catch (error) {
    res.send(error);
  }
});

/**
 * 获取标准实体对象信息。（标准实体的字段，apikey等信息）
 */
//@Api(name="/base/config/object/getStandardConfig")
router.get("/config/object/getStandardConfig", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  try {
    ObjectConfig.getStandardObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let response = {
        code: 200,
        msg: "OK",
        data: configs,
      };
      res.send(response);
    });
  } catch (error) {
    res.send(error);
  }
});

/**
 * 获取自定义实体对象信息。（自定义实体的字段，apikey等信息）
 */
//@Api(name="/base/config/object/getCustomizeConfig")
router.get("/config/object/getCustomizeConfig", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  try {
    ObjectConfig.getCustomizeObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let response = {
        code: 200,
        msg: "OK",
        data: configs,
      };
      res.send(response);
    });
  } catch (error) {
    res.send(error);
  }
});

/**获取系统字段信息。
 */
//@Api(name="/base/config/object/getSystemFields")
router.get("/config/object/getSystemFields", (req, res) => {
  res.send({
    code: 200,
    msg: "",
    data: systemFields,
  });
});

/**创建一个实体或者一个自定义实体。
 */
//@Api(name="/base/config/object/create")
router.post("/config/object/create", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  var busiType = JSON.stringify([
    {
      id: uuid.v4(),
      name: "默认业务类型",
    },
  ]);
  var objectConfig = new ObjectConfig(
    body.icon,
    body.name,
    body.apiKey,
    body.belongId,
    body.props,
    body.state,
    busiType
  );
  objectConfig.save(dataBaseName, function (err) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "恭喜您！创建成功",
        data: objectConfig,
      });
    }
  });
});

/**更新标准实体或者自定义实体字段信息。
 */
//@Api(name="/base/config/object/update")
router.post("/config/object/update", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  var obj = {
    icon: body.icon,
    name: body.name,
    apiKey: body.apiKey,
    belongId: body.belongId,
    props: body.props,
    state: body.state,
    busiType: body.busiType,
  };
  ObjectConfig.update(body.id, obj, dataBaseName, function (err) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "恭喜您！创建成功",
        data: {
          ...obj,
          id: body.id,
        },
      });
    }
  });
});

/**
 * 根据id查询实体配置信息。
 */
//@Api(name="/base/config/object/getById")
router.post("/config/object/getById", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  ObjectConfig.findById(body.id, dataBaseName, function (err, ob) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "查询成功",
        data: ob,
      });
    }
  });
});
/**
 * 根据apiKey查询实体配置信息。
 */
//@Api(name="/base/config/object/getByApiKey")
router.post("/config/object/getByApiKey", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  ObjectConfig.findByApiKey(body.apiKey, dataBaseName, function (err, ob) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "查询成功",
        data: ob,
      });
    }
  });
});

//删除该实体配置信息，也要清空表。
//@Api(name="/base/config/object/delete")
router.post("/config/object/delete", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  ObjectConfig.deleteById(body.id, dataBaseName, function (err, apiKey) {
    console.log("[deleteById]", err);
    console.log("[deleteById]", apiKey);
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: err,
      });
    } else {
      mongodb.connect((error) => {
        if (error) {
          res.send({
            code: 202,
            msg: "服务器错误，请联系管理员",
            data: error,
          });
        }
        const DataBase = mongodb.db(dataBaseName); // 获取数据库
        DataBase.collection(apiKey, function (err, collection) {
          if (err) {
            res.send({
              code: 203,
              msg: "服务器错误，请联系管理员",
              data: err,
            });
          }
          collection.deleteMany({});
          res.send({
            code: 200,
            msg: "删除成功",
            data: body.id,
          });
        });
      });
    }
  });
});

module.exports = router;
